package com.qef.com.mmovie;

import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.avos.avoscloud.AVUser;
import com.bumptech.glide.Glide;
import com.jaeger.library.StatusBarUtil;
import com.orhanobut.logger.Logger;
import com.qef.com.mmovie.activity.LoginActivity;
import com.qef.com.mmovie.api.ApiSever;
import com.qef.com.mmovie.base.BaseMainFragment;
import com.qef.com.mmovie.base.SimpleActivity;
import com.qef.com.mmovie.components.EventUtil;
import com.qef.com.mmovie.entity.User;
import com.qef.com.mmovie.entity.event.UpUserInfoEvent;
import com.qef.com.mmovie.fragment.SubscriptionFragment;
import com.qef.com.mmovie.fragment.UpDataPerson;
import com.qef.com.mmovie.fragment.VideoFragment;
import com.qef.com.mmovie.fragment.laugh_img.LaughImgFragment;
import com.qef.com.mmovie.fragment.video_jc.VideoTopFragment;
import com.qef.com.mmovie.presenter.DowloadPresenter;
import com.qef.com.mmovie.presenter.contract.DowloadContract;
import com.qef.com.mmovie.utils.ShareUtils;
import com.qef.com.mmovie.utils.ToastUtil;
import com.qef.com.mmovie.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.yokeyword.fragmentation.SupportFragment;
import me.yokeyword.fragmentation.helper.FragmentLifecycleCallbacks;
import okhttp3.ResponseBody;

import static com.ashokvarma.bottomnavigation.BottomNavigationBar.BACKGROUND_STYLE_RIPPLE;
import static com.ashokvarma.bottomnavigation.BottomNavigationBar.MODE_FIXED;

public class MainActivity extends SimpleActivity implements BaseMainFragment.OnBackToFirstListener,
        NavigationView.OnNavigationItemSelectedListener, View.OnClickListener, DowloadContract.View {
    private static final String TAG = "Main";
    //    @BindView(R.id.floating_search_view)
//    FloatingSearchView mSearchView;
    @BindView(R.id.bottom_navigation_bar)
    BottomNavigationBar mNavigationView;
    //    @BindView(R.id.imageView_head)
//    ImageView ivHead;
    @BindView(R.id.nav_view)
    NavigationView mNavigationViewx;
    View headView;
    List<SupportFragment> mFragments;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.open_drawerlayout)
    ImageView open_drawerlayout;
    private long firstTime = 0;
    private ApiSever apiSever;

    @Override
    protected int getLayout() {
        //注册eventbus
        EventBus.getDefault().register(this);
        StatusBarUtil.setColor(MainActivity.this, Color.parseColor("#6c4a41"));
        return R.layout.activity_main2;
    }

    @Override
    protected void initEventAndData() {
        //初始化更新信息
//        initUpdata("");

        mFragments = new ArrayList<>();
        mFragments.add(VideoFragment.newInstance());
        mFragments.add(VideoTopFragment.newInstance());
        mFragments.add(LaughImgFragment.newInstance());
        mFragments.add(SubscriptionFragment.newInstance());
        loadMultipleRootFragment(R.id.act_container, 0
                , mFragments.get(0)
                , mFragments.get(1)
                , mFragments.get(2)
                , mFragments.get(3)
        );
        initView();
        initHeadData();
        registerFragmentLifecycleCallbacks(new FragmentLifecycleCallbacks() {
            @Override
            public void onFragmentSupportVisible(SupportFragment fragment) {
                Log.i("MainActivity", "onFragmentSupportVisible--->" + fragment.getClass().getSimpleName());
            }
        });
    }

    private void initUpdata(String s) {
        DowloadPresenter dowloadPresenter = new DowloadPresenter();
        dowloadPresenter.attachView(this);
        dowloadPresenter.getUpdata("");
    }


    /**
     * 初始化用户信息
     */
    private void initHeadData() {
        headView = mNavigationViewx.getHeaderView(0);
        //侧滑菜单对应按钮

        mNavigationViewx.getMenu().getItem(0).setOnMenuItemClickListener(item -> {
                    if (User.isLoginToLogin(this)) {
                        UIHelper.goCollections(MainActivity.this);
                    }
                    return false;
                }
        );

        mNavigationViewx.getMenu().getItem(3).setOnMenuItemClickListener(menuItem -> {
            UIHelper.goFeedBackActivity(MainActivity.this);
            return false;
        });
        mNavigationViewx.getMenu().getItem(1).setOnMenuItemClickListener(menuItem -> {
            if (User.isLoginToLogin(this)) {
                UIHelper.goMyCommented(MainActivity.this);
            }
            return false;
        });
        mNavigationViewx.getMenu().findItem(R.id.nav_setting).setOnMenuItemClickListener(menuItem -> {
            UIHelper.goSettingActivity(MainActivity.this);
            return false;
        });
        mNavigationViewx.getMenu().findItem(R.id.nav_share).setOnMenuItemClickListener(menuItem -> {
            ShareUtils.shareGirl("MMove下载地址:\n"
                    , "http://..........", this);
            return false;
        });
        mNavigationViewx.getMenu().findItem(R.id.nav_slideshow).setOnMenuItemClickListener(menuItem -> {
            ToastUtil.showToast(this, "功能暂未开放！");
            return false;
        });

        ImageView headImg = (ImageView) headView.findViewById(R.id.imageView_head);
        headImg.setOnClickListener(this);
        TextView username = (TextView) headView.findViewById(R.id.username);
        TextView userId = (TextView) headView.findViewById(R.id.user_id);
        username.setOnClickListener(this);
        if (User.isLogin()) {
            if (null != User.getCurrenUser() & null != User.getHead())
                Glide.with(this).load(User.getCurrenUser().get("head")).into(headImg);

//            AVUser user = Constants.getUserInfo();
            username.setText(null == AVUser.getCurrentUser().get("alias") ?
                    "" : AVUser.getCurrentUser().get("alias").toString());
            userId.setText(User.getCurrenUser().getUsername());
        } else {
            username.setText("登陆注册");
            userId.setText("");
            headImg.setImageDrawable(getResources().getDrawable(R.mipmap.portrait_default_big_2x));
        }
    }


    private void initView() {
        open_drawerlayout.setOnClickListener(this);
        mNavigationView
                .addItem(new BottomNavigationItem(R.drawable.movie_icon, getString(R.string.choiceness)).setActiveColor("#6c4a41").setInActiveColor("#CCCCCC"))
                .addItem(new BottomNavigationItem(R.mipmap.icon2, "搞笑").setActiveColor("#008867"))
                .addItem(new BottomNavigationItem(R.drawable.book_icon, "分类").setActiveColor("#8b6b64"))
                .addItem(new BottomNavigationItem(R.drawable.newspaper_icon, "发现").setActiveColor("#485A66"))
                .initialise();
        mNavigationView.setBackgroundStyle(BACKGROUND_STYLE_RIPPLE);
        mNavigationView.setMode(MODE_FIXED);
        mNavigationView.setAutoHideEnabled(true);
        mNavigationView.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
            @Override
            public void onChildViewAdded(View view, View view1) {
                EventBus.getDefault().post(0);
            }

            @Override
            public void onChildViewRemoved(View view, View view1) {
                EventBus.getDefault().post(1);
            }
        });
        mNavigationView.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                showHideFragment(mFragments.get(position));
                switch (position) {
                    case 0:
                        StatusBarUtil.setColor(MainActivity.this, Color.parseColor("#6c4a41"));
                        break;
                    case 1:
                        StatusBarUtil.setColor(MainActivity.this, Color.parseColor("#008867"));
                        break;
                    case 2:
                        StatusBarUtil.setColor(MainActivity.this, Color.parseColor("#8b6b64"));
                        break;
                    case 3:
                        StatusBarUtil.setColor(MainActivity.this, Color.parseColor("#485A66"));
                        break;
                }
            }

            @Override
            public void onTabUnselected(int position) {
            }

            @Override
            public void onTabReselected(int position) {
            }
        });
    }

//    @Subscribe
//    public void hide(String isHide) {
//        if (isHide.equals("true")) {
//            mSearchView.setVisibility(View.GONE);
//        } else {
//            mSearchView.setVisibility(View.VISIBLE);
//        }
//    }

    @Override
    public void onStart() {
        super.onStart();
//        EventUtil.register(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventUtil.unregister(this);
    }

    @Override
    public void onBackToFirstFragment() {
        mNavigationView.selectTab(0);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        return super.onTouchEvent(event);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {


        return false;
    }

    @Override
    public void onClick(View v) {
//        SnackbarUtil.ShortSnackbar(mNavigationView, "----------", SnackbarUtil.Info).show();
//        startChildFragment();
//        showHideFragment(LoginFragment.newInstance());
        switch (v.getId()) {
            case R.id.imageView_head:
                if (User.isLogin()) {
                    startActivity(new Intent().setClass(this, UpDataPerson.class));
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.username:
                if (!User.isLogin()) {
                    UIHelper.goLoginActivity(this);
                }
                break;
            case R.id.nav_setting:
                UIHelper.goSettingActivity(this);
                break;
            case R.id.nav_share:
                ShareUtils.shareGirl("MMove下载地址:\n"
                        , "http://..........", this);
                break;
            case R.id.nav_slideshow:
                ToastUtil.showToast(this, "功能暂未开放！");
                break;
            case R.id.nav_camera:
                if (User.isLoginToLogin(this))
                    UIHelper.goCollections(this);
                break;
            case R.id.open_drawerlayout:
                if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
                    drawerLayout.closeDrawer(GravityCompat.START);
                } else {
                    drawerLayout.openDrawer(GravityCompat.START);
                }
                break;
        }

    }

    private void startChildFragment() {
        startActivity(new Intent(this, LoginActivity.class));

//        EventUtil.sendEvent(true + "");
//        LoginFragment fragment = LoginFragment.newInstance();
//        // 这里是使用SharedElement的用例
//
//        // LOLLIPOP(5.0)系统的 SharedElement支持有 系统BUG， 这里判断大于 > LOLLIPOP
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
//            fragment.setExitTransition(new Fade());
//            fragment.setEnterTransition(new Slide());
//            fragment.setSharedElementReturnTransition(new DetailTransition());
//            fragment.setSharedElementEnterTransition(new DetailTransition());
//
//            // 25.1.0以下的support包,Material过渡动画只有在进栈时有,返回时没有;
//            // 25.1.0+的support包，SharedElement正常
////            fragment.transaction()
////                    .addSharedElement(vh.imageView, getString(R.string.image_transition))
//////                        .addSharedElement(((VideoAdapter.MyHolder) vh).textView,"tv")
////                    .commit();
//        }
//        getTopFragment().start(fragment);
////        start(fragment);
//        mNavigationView.hide();
    }

    public void hindbar() {
        mNavigationView.hide();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEvent(UpUserInfoEvent msg) {
        initHeadData();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(this, "再点一次退出", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
                Intent intent = new Intent();
                intent.setAction("finishApp");
                sendBroadcast(intent);
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private boolean writeResponseBodyToDisk(ResponseBody body) {
        try {
            // todo change the file location/name according to your needs
            File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + "Future Studio Icon.png");

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;

                    Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
                }

                outputStream.flush();

                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }

    @Override
    public void showContent(ResponseBody responseBody) {
        Logger.i("------------>", "下载成功");
    }

    @Override
    public void error(Throwable throwable) {
        Logger.i("------------>", "下载失败");
    }
}

